<?php

namespace App\Services;

use GuzzleHttp\Client;

class WeatherService
{
    protected $guzzleOptions = [];

    public function __construct()
    {
        $this->key = env('amap_key');
    }

    public function getHttpClient()
    {
        return new Client($this->guzzleOptions);
    }

    public function setGuzzleOptions(array $options)
    {
        $this->guzzleOptions = $options;
    }

    public function getWeather($city, string $type = 'base', string $format = 'json')
    {
        $url = 'https://restapi.amap.com/v3/weather/weatherInfo';

        if (!in_array(strtolower($format), ['xml', 'json'])) {
            return false;
        }

        if (!in_array(strtolower($type), ['base', 'all'])) {
            return false;
        }

        $query = array_filter([
            'key'        => $this->key,
            'city'       => $city,
            'output'     => strtolower($format),
            'extensions' => strtolower($type),
        ]);

        try {
            $response = $this->getHttpClient()->get($url, [
                'query' => $query,
            ])->getBody()->getContents();

            return 'json' === $format ? \json_decode($response, true) : $response;
        } catch (\Exception $e) {
            return $e;
        }
    }
}